from django.utils import timezone
from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
from django.conf import settings
from django.contrib.gis.db import models as gis_models
from django.contrib.gis.geos import Point as GisPoint

from common.query_set import RequestQuerySet


class Firm(models.Model):
    """企业"""
    __firm_status__ = (
        (0, '正常'),
        (1, '停用')
    )

    name = models.CharField(max_length=256, verbose_name='企业名')
    contact = models.CharField(max_length=128, blank=True, null=True, verbose_name='联系人')
    mobile = models.CharField(max_length=11, blank=True, null=True, verbose_name='手机号码')
    max_user_num = models.IntegerField(default=1, verbose_name='最大账号数量')
    current_user_num = models.IntegerField(default=0, verbose_name='当前账号数量')
    longitude = models.FloatField(blank=True, null=True, verbose_name='经度')
    latitude = models.FloatField(blank=True, null=True, verbose_name='纬度')
    address = models.CharField(blank=True, null=True, max_length=512, verbose_name='地址')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    status = models.SmallIntegerField(default=0, choices=__firm_status__, verbose_name='状态')

    class Meta:
        verbose_name = '企业'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class User(AbstractUser):
    """用户"""
    qq = models.CharField(max_length=20, blank=True, null=True, verbose_name='QQ号码')
    mobile = models.CharField(max_length=11, blank=True, null=True, verbose_name='手机号码')
    expire_time = models.DateField(default=timezone.now, verbose_name='到期时间')
    firm = models.ForeignKey(Firm, null=True, blank=True, on_delete=models.CASCADE, verbose_name='所属企业')
    global_user = models.BooleanField(default=False, verbose_name='全局用户')
    default_point = gis_models.PointField(null=False, blank=False, verbose_name='默认坐标', default=GisPoint(settings.SCENIC_CENTER.x, settings.SCENIC_CENTER.y))
    default_polygon = gis_models.PolygonField(blank=False, null=False, verbose_name='默认区域', default=settings.SCENIC_AREA)
    default_linestring = gis_models.LineStringField(null=False, blank=False, verbose_name='默认路线', default=settings.SCENIC_LINE)

    objects = UserManager()
    request_objects = RequestQuerySet.as_manager()

    def titleName(self):
        return self.last_name + ' ' + self.first_name

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        ordering = ['-id']
        indexes = [
            models.Index(fields=['firm'])
        ]

    def __str__(self):
        return self.username
